<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col
        :span="24"
        style="text-align: left;"
      >
        <el-date-picker
          v-model="tableDatas.filters.dates"
          type="daterange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY/MM/DD"
          value-format="YYYYMMDD"
          @change="getTableDatas"
        />
        <el-input
          style="display:inline;margin: 0px 12px"
          v-model="tableDatas.filters.searchText"
          clearable
        >
          <template #prepend>搜索</template>
        </el-input>

        <el-checkbox-group
          v-model="tableDatas.filters.wmList"
          @change="tableDatas.filters.wmListChange"
          style="display:inline;margin: 0px 12px;height:32px"
        >
          <el-checkbox
            label="内贸"
            :value="false"
          />
          <el-checkbox
            label="外贸"
            :value="true"
          />
        </el-checkbox-group>

        <el-button
          type="success"
          @click="addBtnClick"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <div v-if="item.isDate">
              <el-date-picker
                v-model="dialogDatas.currentData[item.value]"
                :type="item.dateOption ? item.dateOption.type : 'date'"
                :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
                :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
                :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
                :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
                :disabled="item.disable"
              />
            </div>

            <div
              v-else-if="item.isSelect"
              style="width: 100%"
            >
              <el-select
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
                filterable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div
              v-else-if="item.isSwitch"
              style="width: 100%"
            >
              <el-switch
                v-model="dialogDatas.currentData[item.value]"
                inline-prompt
                active-text="启用"
                inactive-text="不启用"
                :active-value="item.trueValue"
                :inactive-value="item.falseValue"
                :disabled="item.disable"
              />
            </div>
            <div
              v-else
              style="width: 100%"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-row
      class="marginTop10"
      :gutter="10"
    >
      <el-col :span="8">
        <el-table
          :data="tableDatas.typeGroupList"
          @row-click="tableDatas.handleRowClick"
          :row-class-name="tableDatas.rowClassName"
          border
          max-height="90vh"
        >
          <!-- 表格列定义 -->
          <el-table-column
            prop="TYPE"
            label="类型"
          ></el-table-column>
          <el-table-column
            prop="QTY"
            label="数量"
          ></el-table-column>
        </el-table>
      </el-col>

      <el-col :span="16">

        <el-table
          :data="tableDatas.tableDatasAfterPage"
          stripe
          border
          empty-text="无数据"
          max-height="90vh"
        >
          <el-table-column
            v-for="column in tableDatas.tableColumns"
            :type="column.type"
            :prop="column.prop"
            :label="column.label"
            :align="column.align"
            :width="column.width"
            :sortable="column.sortable"
          >
            <template
              #default="scope"
              v-if="column.prop =='operate'"
            >
              <div>
                <el-button
                  type="success"
                  @click="tableDatas.editBtnClick(scope.row)"
                >修改</el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="确定删除该条记录?"
                  @confirm="tableDatas.deleteBtnClick(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
    </el-row>

    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import useMyXlsx from '@/hooks/useMyXlsx';

export default {
  name: '',
  setup () {
    let loading = ref(false);
    let addBtnClick = function () {
      // showFormDialog();
      let xlsx = useMyXlsx();
      let columns = JSON.parse(JSON.stringify(tableDatas.tableColumns));
      // 删掉序号列,添加外贸列
      columns.splice(0, 1, { prop: 'IS_WM', label: '是否外贸' });
      let exportOptions = xlsx.getExportOptionFromColumns(columns, 'prop', 'label', tableDatas.ALL_List);
      xlsx.exportDatas(tableDatas.ALL_List, exportOptions, '机械手搭载驱动器内外贸数据.xlsx');
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "MATCODE",
          "label": "物料",
          "isDate": false
        },
        {
          "value": "TYPE",
          "label": "类型",
          "isDate": false
        },
        {
          "value": "QTY",
          "label": "数量",
          "isDate": false
        },
        // {
        //   "value": "EMP_DEPARTMENT",
        //   "label": "部门",
        //   "isDate": false,
        //   "disable": false,
        //   "isSelect": true,
        //   "selectOptions": [
        //     {
        //       "value": "value_1",
        //       "label": "label_1"
        //     },
        //     {
        //       "value": "value_2",
        //       "label": "label_2"
        //     }
        //   ]
        // },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // }
      ],
      confirmBtnClick: function () {
        loading.value = true;
        let row = dialogDatas.currentData;
        let MATCODE = row.MATCODE ? row.MATCODE : v4();

        let params = `${MATCODE}`
          + `🈹${dialogDatas.currentData.F_METCODE}`
          + `🈹${dialogDatas.currentData.QTY}`;
        myAxios.post('添加或更新', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = async function () {
      loading.value = true;
      let startDate = tableDatas.filters.dates[0];
      let endDate = tableDatas.filters.dates[1];
      if (!startDate) {
        loading.value = false;

        return;
      }
      // console.log('table :>> ', tableDatas.filters.dates);


      //#region 获取智联业务员,根据业务员编码和业务组来分内外贸

      let zlUserRes = await myAxios.get('MES智联业务员查询', ``, '9911');
      // 获取所有有编码的
      let zlUserList = zlUserRes.map(item => {
        if (item['编码']) {
          return item;
        }
      }).filter(item => item);
      // 根据编码分组,只保留每组第一个,把业务组属性用,号连接起来
      for (let i = 0; i < zlUserList.length; i++) {
        let item = zlUserList[i];
        let CODE = item['编码'];
        let groupList = zlUserList.filter(el => el['编码'] == CODE);
        if (groupList.length > 1) {
          for (let j = 1; j < groupList.length; j++) {
            groupList[0]['业务组'] += ',' + groupList[j]['业务组'];
            zlUserList.splice(zlUserList.indexOf(groupList[j]), 1);
          }
        }
      }
      // console.log('zlUserList :>> ', zlUserList);
      let zlWmList = zlUserList.map(item => {
        if (item['业务组'].includes('智联业务外贸组')) {
          return item['编码'];
        }
      }).filter(item => item);
      // console.log('zlWmList :>> ', zlWmList);

      //#endregion

      let rlParams = `${startDate}🈹${endDate}🈹9911🈹X🈹🈹🈹9911`;
      let rlRes = await myAxios.getSap('SAP销售与出运统计(销售组织与工厂)', rlParams, '9900');
      console.log('rlRes :>> ', rlRes);
      let rlList = rlRes.TableSet.IT_DATA1.map(item => item.MATNR);
      let zlParams = `🈹${rlList.join(',')}🈹SER01🈹${startDate}🈹${endDate}🈹🈹601`;
      let zlProsnRes = await myAxios.getSap('SAP获取物料序列号移动记录', zlParams, '9911');
      console.log('zlProsnRes :>> ', zlProsnRes);
      let zlList = zlProsnRes.TableSet.R_OBJK.map(item => item.SERNR);
      // zlList数量太多,每一百个一组来获取数据
      let qtyList = [];
      for (let i = 0; i < zlList.length; i += 50) {
        let qtyList100 = zlList.slice(i, i + 50);
        let qtyParams = `${qtyList100.join('\',\'')}`;
        let qtyProsnRes = await myAxios.get('陈帅廷查询智联流水号驱动器使用数详情', qtyParams, '9911');
        let typeGroupList_WM = [];
        let typeGroupList_NM = [];
        qtyProsnRes.forEach(item => {
          // CONTRACTNO "HTZL250221-2702"
          // SERNR 获取上面的27
          let CONTRACTNO = item['CONTRACTNO'];
          let SERNR = CONTRACTNO.split('-')[1].substring(0, 2);
          let TYPE = item['TYPE'];

          if (zlWmList.includes(SERNR)) {
            item['IS_WM'] = true;

            let TYPE_GROUP = tableDatas.typeGroupList_WM.find(el => el.TYPE == TYPE);
            if (TYPE_GROUP) {
              TYPE_GROUP.QTY += item['BOMDOSAGE'];
            }
            else {
              tableDatas.typeGroupList_WM.push({
                TYPE: TYPE,
                QTY: item['BOMDOSAGE'],
              });
            }
            tableDatas.WM_List.push({ ...item });
          }
          else {
            item['IS_WM'] = false;

            let TYPE_GROUP = tableDatas.typeGroupList_NM.find(el => el.TYPE == TYPE);
            if (TYPE_GROUP) {
              TYPE_GROUP.QTY += item['BOMDOSAGE'];
            }
            else {
              tableDatas.typeGroupList_NM.push({
                TYPE: TYPE,
                QTY: item['BOMDOSAGE'],
              });
            }
            tableDatas.NM_List.push({ ...item });
          }

          let TYPE_GROUP = tableDatas.typeGroupList_ALL.find(el => el.TYPE == TYPE);
          if (TYPE_GROUP) {
            TYPE_GROUP.QTY += item['BOMDOSAGE'];
          }
          else {
            tableDatas.typeGroupList_ALL.push({
              TYPE: TYPE,
              QTY: item['BOMDOSAGE'],
            });
          }
          tableDatas.ALL_List.push({ ...item });
        });
        qtyList.push(...qtyProsnRes);
      }
      // console.log('tableDatas.typeGroupList_WM :>> ', tableDatas.typeGroupList_ALL);
      // console.log('tableDatas.WM_List :>> ', tableDatas.ALL_List);
      // tableDatas.oritableData = qtyList;
      loading.value = false;
    };

    onMounted(() => {
      getTableDatas();
    });

    let searchKeys = ['MATCODE', 'TYPE'];
    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',
        dates: ['', ''],
        wmList: [true, false],

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },

      typeGroupList: computed(() => {
        let fData = [];
        if (tableDatas.filters.wmList && tableDatas.filters.wmList.length) {
          if (tableDatas.filters.wmList.length == 2) {
            fData = tableDatas.typeGroupList_ALL;
          }
          else if (tableDatas.filters.wmList.length == 1) {
            let IS_WM = tableDatas.filters.wmList[0];
            fData = IS_WM ? tableDatas.typeGroupList_WM : tableDatas.typeGroupList_NM;
          }
        }
        return fData;
      }),
      tableDatasAfterFilter: computed(() => {
        let fData = [];
        if (tableDatas.filters.wmList && tableDatas.filters.wmList.length) {
          if (tableDatas.filters.wmList.length == 2) {
            fData = tableDatas.ALL_List;
          }
          else if (tableDatas.filters.wmList.length == 1) {
            let IS_WM = tableDatas.filters.wmList[0];
            fData = IS_WM ? tableDatas.WM_List : tableDatas.NM_List;
          }
          if (tableDatas.filters.searchText) {
            let searchText = tableDatas.filters.searchText;
            fData = fData.filter(item => {
              return searchKeys.some(key => {
                return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
              });
            });
          }
          if (tableDatas.selectedRow && tableDatas.selectedRow.TYPE) {
            fData = fData.filter(item => {
              return tableDatas.selectedRow.TYPE == item.TYPE;
            });
          }
        }
        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),
      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "MATCODE",
          "label": "物料",
          "align": "center",
          "sortable": true,
        },
        // {
        //   "prop": "MATNAME",
        //   "label": "物料描述",
        //   "align": "center",
        //   "sortable": true,
        // },
        {
          "prop": "TYPE",
          "label": "类型",
          "align": "center",
          "sortable": true,
        },
        {
          "prop": "JM_WORKORDERID",
          "label": "订单号",
          "align": "center",
          "sortable": true,
        },
        {
          "prop": "CONTRACTNO",
          "label": "合同号",
          "align": "center",
          "sortable": true,
        },
        {
          "prop": "BOMDOSAGE",
          "label": "数量",
          "align": "center",
          "sortable": true,
        },
        // {
        // 	"prop": "operate",
        // 	"label": "操作",
        // 	"align": "center",
        // 	"width": 170
        // }
      ],
      typeGroupList_WM: [],
      typeGroupList_NM: [],
      typeGroupList_ALL: [],
      WM_List: [],
      NM_List: [],
      ALL_List: [],
      oritableData: [
      ],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let MATCODE = row.MATCODE;

        let params = `${MATCODE}`;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },

      selectedRow: {},
      handleRowClick (row) {
        // 更新选中行
        tableDatas.selectedRow = row;

      },
      // 动态设置行的类名
      rowClassName ({ row }) {
        return row === tableDatas.selectedRow ? 'selected-row' : '';
      }
    });

    return {
      loading,
      addBtnClick,
      getTableDatas,
      dialogDatas,
      tableDatas
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
.selected-row {
  background-color: #f0f9eb !important; /* 可替换为任意颜色 */
}
</style>

